import axios from 'axios'
import { takeEvery, put } from 'redux-saga/effects'
import { modify_active, modify_active_success, modify_todo_edit, modify_todo_edit_success, clear_active_todo, clear_active_todo_success, add_todo, add_todo_success, load_todo, load_todo_success, remove_todo, remove_todo_success, modify_todo, modify_todo_success } from '../actions/todo.actions'

function* load_todos() {
    let todos = yield axios.get('http://localhost:3005/api/todos').then(res => res.data)
    yield put(load_todo_success(todos))
}

function* add_todos(action) {
    let task = yield axios.post('http://localhost:3005/api/todos', { taskName: action.payload }).then(res => res.data)
    yield put(add_todo_success(task.task))
}
function* remove_todos(action) {
    console.log(action);
    let res = yield axios.delete('http://localhost:3005/api/todos', {
        params: {
            id: action.payload
        }
    }).then(res => res.data)
    console.log(res);

    yield put(remove_todo_success(res.tasks.id))
}
function* modify_todos(action) {
    let res = yield axios.put('http://localhost:3005/api/todos/isCompleted', action.payload).then(res => res.data)
    yield put(modify_todo_success(res.task))
}

function* clear_active_todos() {
    yield axios.delete('http://localhost:3005/api/todos/clearCompleted')
    yield put(clear_active_todo_success())
}

function* modify_todo_edits(action) {
    let res = yield axios.put('http://localhost:3005/api/todos/isEditing', action.payload).then(res => res.data)
    yield put(modify_todo_edit_success(res.task))
}
function* modify_actives(action) {
    yield axios.put('http://localhost:3005/api/todos', action.payload)
    yield put(modify_active_success(action.payload))
}

export default function* todoSage() {
    yield takeEvery(load_todo, load_todos)
    yield takeEvery(add_todo, add_todos)
    yield takeEvery(remove_todo, remove_todos)
    yield takeEvery(modify_todo, modify_todos)
    yield takeEvery(clear_active_todo, clear_active_todos)
    yield takeEvery(modify_todo_edit, modify_todo_edits)
    yield takeEvery(modify_active, modify_actives)
}